package com.songtech.server.frame.chain.handler;

import com.songtech.server.Calculation.EleFenceCalculation;
import com.songtech.server.Jedis.JedisBaseDao;
import com.songtech.server.constant.KeysConstant;
import com.songtech.server.constant.enumConstant.AlertEnum;
import com.songtech.server.entry.AlertEntry;
import com.songtech.server.entry.PositionProtocal;
import com.songtech.server.utils.GetKeysUtils;
import com.songtech.web.entry.SysPosElefence;

import java.io.Serializable;

/**
 * Create By YINN on 2018/4/26 17:56
 * Description : 电子围栏监听器
 */
public class ElefenceHandler implements BaseChainHandler {

    private final static String ALERT = KeysConstant.ALERT;

    private PositionProtocal entry;

    private JedisBaseDao<Serializable> jedisBaseDao;


    /**
     * 构造器
     * */
    public ElefenceHandler(PositionProtocal entry, JedisBaseDao<Serializable> jedisBaseDao) {
        this.entry = entry;
        this.jedisBaseDao = jedisBaseDao;
    }

    @Override
    public void exec() {

        elefenceCal(entry, jedisBaseDao);

    }

    /***
     * 电子围栏
     * @param  present 当前点位信息对象
     * */
    private void elefenceCal(PositionProtocal present, JedisBaseDao<Serializable> jedisBaseDao) {

        String imei = present.getImei();

        //获取电子围栏实体对象
        SysPosElefence fence =
                (SysPosElefence) jedisBaseDao.get(GetKeysUtils.combineAnyKeys(KeysConstant.ELE_FENCE, imei));
        if (fence == null) {
            return;
        }

        //获取上一点位对象
        PositionProtocal previous = (PositionProtocal) jedisBaseDao.get(present.getRedisKey());
        if (previous == null) {
            return;
        }

        //获取电子围栏算法 并执行计算
        EleFenceCalculation calculation = new EleFenceCalculation(present, previous, fence);
        //计算
        AlertEnum anEnum = calculation.cal();

        if (anEnum != null) {

            AlertEntry alertEntry = new AlertEntry(anEnum.getValue(),
                    anEnum.getName(),
                    present.getRecordTime());

            alertEntry.setImei(present.getImei());
            alertEntry.setLocType(present.getLocationType());

            System.out.println("电子围栏告警!");

            //将对象存入alert_imei键(告警查询队列)
            jedisBaseDao.rpush(GetKeysUtils.combineAnyKeys(ALERT, imei), alertEntry);

            alertEntry.setImei(imei);
            //redis记录告警推送消息队列
            jedisBaseDao.rpush(ALERT, alertEntry);
        }
    }


}
